import modelExtend from 'dva-model-extend'
import api from 'api'
import { pageModel } from 'utils/model'
const { pathToRegexp } = require("path-to-regexp")
const { queryAdminContentCategoryList,queryAdminContentCategoryDetails,
  updateAdminContentCategory, createAdminContentCategory,deleteAdminContentCategory,queryAdminContentCategoryTree } = api

export default modelExtend(pageModel, {
  namespace: 'admin_content_category',

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathToRegexp('/admin_content_category').exec(location.pathname)) {
          // dispatch({
          //   type: 'queryCategoryTree',
          // })
          dispatch({
            type: 'query',
          })
        }
      })
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const data = yield call(queryAdminContentCategoryList, payload)
      console.log(data)
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.payload.list,
            pagination: {
              current: Number(payload?.pageNum) || 1,
              pageSize: Number(payload?.pageSize) || 1000,
              total: data.total,
            },
          },
        })
      } else {
        throw data
      }
    },
    //查询同步分类树
    *queryCategoryTree({payload}, {call, put}) {
      const data = yield  call(queryAdminContentCategoryTree)
      if(data.success) {
        yield  put({type: 'updateState', payload: {categoryTree: data.payload}})
      }
    },
    //查询分类详情
    *queryDetails({payload}, {call,put}) {
        //查询指定分类数据
      const data = yield call(queryAdminContentCategoryDetails, payload)
      if(data.success) {
        yield put({type: 'updateState', payload: {item: data.payload}})
      }
    },
   *create({ payload }, { call, put }) {
      const data = yield call(createAdminContentCategory, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },

    *update({ payload }, { select, call, put }) {
      const newUser = { ...payload }
      const data = yield call(updateAdminContentCategory, newUser)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },
    *delete({ payload }, { select, call, put }) {
      const data = yield call(deleteAdminContentCategory, {ids:payload})
      if (!data.success) {
        throw data
      }
    }
  },
  reducers: {
    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal(state) {
      return { ...state, modalVisible: false }
    },
  },
})
